from typing import Any, Dict
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from database import get_db
from models import User, Drone, FlightRoute
from datetime import datetime, timedelta
from api.deps import get_current_active_user

router = APIRouter()


@router.get("/dashboard", response_model=Dict[str, Any])
async def get_dashboard_statistics(
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
) -> Dict[str, Any]:
    """
    获取仪表盘统计数据
    """
    try:
        # 获取当前时间
        now = datetime.utcnow()
        
        # 计算上个月的起始和结束时间
        last_month_start = now.replace(day=1) - timedelta(days=1)
        last_month_start = last_month_start.replace(day=1, hour=0, minute=0, second=0, microsecond=0)
        
        # 计算昨天的起始和结束时间
        yesterday_start = now - timedelta(days=1)
        yesterday_start = yesterday_start.replace(hour=0, minute=0, second=0, microsecond=0)
        yesterday_end = now.replace(hour=0, minute=0, second=0, microsecond=0)
        
        # 获取用户总数
        total_users = db.query(User).count()
        
        # 获取上个月的用户数
        last_month_users = db.query(User).filter(
            User.created_at < last_month_start.replace(month=last_month_start.month + 1) if last_month_start.month < 12 else last_month_start.replace(month=1, year=last_month_start.year + 1),
            User.created_at >= last_month_start
        ).count()
        
        # 计算用户变化百分比
        users_change = 0
        if last_month_users > 0:
            users_change = round(((total_users - last_month_users) / last_month_users) * 100)
        
        # 获取无人机总数
        total_drones = db.query(Drone).count()
        
        # 获取上个月的无人机数
        last_month_drones = db.query(Drone).filter(
            Drone.created_at < last_month_start.replace(month=last_month_start.month + 1) if last_month_start.month < 12 else last_month_start.replace(month=1, year=last_month_start.year + 1),
            Drone.created_at >= last_month_start
        ).count()
        
        # 计算无人机变化百分比
        drones_change = 0
        if last_month_drones > 0:
            drones_change = round(((total_drones - last_month_drones) / last_month_drones) * 100)
        
        # 获取在线无人机数（假设status=1表示在线）
        active_drones = db.query(Drone).filter(Drone.status == 1).count()
        
        # 获取昨天的在线无人机数
        yesterday_active_drones = db.query(Drone).filter(
            Drone.status == 1,
            Drone.updated_at >= yesterday_start,
            Drone.updated_at < yesterday_end
        ).count()
        
        # 计算在线无人机变化百分比
        active_drones_change = 0
        if yesterday_active_drones > 0:
            active_drones_change = round(((active_drones - yesterday_active_drones) / yesterday_active_drones) * 100)
        
        # 获取航线总数
        total_routes = db.query(FlightRoute).count()
        
        # 获取上个月的航线数
        last_month_routes = db.query(FlightRoute).filter(
            FlightRoute.created_at < last_month_start.replace(month=last_month_start.month + 1) if last_month_start.month < 12 else last_month_start.replace(month=1, year=last_month_start.year + 1),
            FlightRoute.created_at >= last_month_start
        ).count()
        
        # 计算航线变化百分比
        routes_change = 0
        if last_month_routes > 0:
            routes_change = round(((total_routes - last_month_routes) / last_month_routes) * 100)
        
        # 获取最近活动（最近10条记录）
        recent_activities = db.query(User.username, FlightRoute.name, FlightRoute.created_at).join(
            FlightRoute, FlightRoute.created_by == User.id
        ).order_by(FlightRoute.created_at.desc()).limit(10).all()
        
        activities_list = [
            {
                "time": activity.created_at.strftime("%Y-%m-%d %H:%M"),
                "user": activity.username,
                "action": f"创建了新航线: {activity.name}",
                "status": "success"
            }
            for activity in recent_activities
        ]
        
        # 返回统计数据
        return {
            "code": 200,
            "message": "success",
            "data": {
                "stats": {
                    "totalUsers": total_users,
                    "usersChange": users_change,
                    "totalDrones": total_drones,
                    "dronesChange": drones_change,
                    "activeDrones": active_drones,
                    "activeDronesChange": active_drones_change,
                    "totalRoutes": total_routes,
                    "routesChange": routes_change
                },
                "recentActivities": activities_list
            }
        }
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取统计数据失败: {str(e)}")